<?php
namespace app\admin\controller;
use app\common\controller\CommonController;
use app\common\errcode\AdminErrCode;
use app\common\errcode\AdminErrMsg;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
/**
 * 后台基础控制器
 */
class BaseController extends CommonController
{
    protected $uid;

    public function __construct()
    {
        parent::__construct();
        $this->jwt = trim(str_replace('Bearer','',$this->request->header('authorization')));
        $this->uid = $this->auth($this->jwt)['id'];
    }
    
    /**
     * 登录校验
     * @param string jwt jwt-token字符串
     */
    protected function auth($token)
    {
        try{
            if(empty($token)){
                echo json_encode(['code' => AdminErrCode::JWT_ERROR,'msg' => AdminErrMsg::JWT_ERROR],JSON_UNESCAPED_UNICODE);exit;
            } 
            $key = Config('admin_key');
            $jwt = json_encode(JWT::decode($token, new Key($key,'HS256')));
            $authInfo = json_decode($jwt, true);
            if(!empty($authInfo['userinfo'])){
                return $authInfo['userinfo'];
            }else{
                echo json_encode(['code' => AdminErrCode::JWT_ERROR,'msg' => AdminErrMsg::JWT_ERROR],JSON_UNESCAPED_UNICODE);exit;
            }
        } catch (\Firebase\JWT\SignatureInvalidException $e) {
            echo json_encode(['code' => AdminErrCode::JWT_ERROR,'msg' => AdminErrMsg::JWT_ERROR],JSON_UNESCAPED_UNICODE);exit;
        } catch (\Firebase\JWT\ExpiredException $e){
            echo json_encode(['code' => AdminErrCode::JWT_EXPIRE,'msg' => AdminErrMsg::JWT_EXPIRE],JSON_UNESCAPED_UNICODE);exit;
        } catch (\Exception $e){
            echo json_encode(['code' => AdminErrCode::JWT_ERROR,'msg' => AdminErrMsg::JWT_ERROR],JSON_UNESCAPED_UNICODE);exit;
        }
    }
    
    /**
     * 获取用户信息
     */
    public function get_user_info()
    {
        try{
            $token = $this->jwt;
            $key = Config('admin_key');
            $decoded = json_encode(JWT::decode($token, new Key($key,'HS256')));
            $decoded = json_decode($decoded,true);
            if(!empty($decoded['userinfo'])) return $decoded['userinfo'];
            echo json_encode(['code' => AdminErrCode::JWT_ERROR,'msg' => AdminErrMsg::JWT_ERROR],JSON_UNESCAPED_UNICODE);exit;
        }catch(\Exception $e){
            echo json_encode(['code' => AdminErrCode::JWT_ERROR,'msg' => AdminErrMsg::JWT_ERROR],JSON_UNESCAPED_UNICODE);exit;
        }
    }
}